const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const md5 = require('md5-node')
const { enCode, deCode } = require('../util/token/auth')
const { USER_NO_PROMESSION, TOKEN_EXPIRED, PARAM_NOT_VALID, SUCCESS, USER_PWD_ERROR, USER_ACCOUNT_NOTFOUND, USER_ACCOUNT_EXIST, USER_NOT_LOGIN } = require('../util/respone/index')

// 过期时间
const tokenExpiresTime = 1000 * 60 * 60 * 24 * 7

let admin = new Router()

// 登录
admin.post('/login', async (ctx, next) => {
  let postParams = ctx.request.body;
  // md5加密 用户发送过来的 账号+密码
  let checkHash = md5(postParams.username + postParams.password)
  
  await mysql.check(`SELECT * FROM user where username = "${postParams.username}"`)
    .then(async res => {
    if (res.length > 0) {
      let data = res[0]
      // 验证数据库 中 用户名和密码 是否一致
      if ( data.passHash === checkHash ) {
        // 登录成功 加密发送token
        let payload = {
          exp: Date.now() + tokenExpiresTime,
          name: data.userName,
          auth: data.auth
        }
        let token = enCode(payload)
        await SUCCESS(ctx,{ token }, '登录成功')
      } else {
        // 登录失败 发送拒绝回应
        await USER_PWD_ERROR(ctx)
      }
    } else {
      // 数据库中没有该用户
      await USER_ACCOUNT_NOTFOUND(ctx)
    }
  })
})



module.exports = { admin }   